package com.summer.safe.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义标签工具类
 *
 *
 */
public class TagUtil {
    /**
     * 格式化select数据
     *
     * @param o1 数据集
     * @param s1
     * @param s2
     * @return
     */
    public static Object formatData(Object o1, String s1, String s2) {
        if (StringUtils.isEmpty(s1) && StringUtils.isEmpty(s2)) {
            s1 = "value";
            s2 = "label";
        }
        if (o1 == null) {
            return null;
        }
        if (o1 instanceof List) {
            Map<Object, Object> items = new LinkedHashMap<>();
            for (Object o : (List) o1) {
                items.put(Reflections.invokeGetter(o, s1), Reflections.invokeGetter(o, s2));
            }
            return items;
        } else if (o1 instanceof Map) {
            return o1;
        } else if (o1 instanceof String) {
            return JSON.parseObject(o1.toString(), new TypeReference<Map<String, Object>>() {
            });
        }
        return null;
    }

    public static Object formatData(Object o1) {
        return formatData(o1, null, null);
    }

    /**
     * 多层级控件名id处理
     *
     * @param s1
     * @return
     */
    public static String format(String s1) {
        StringBuffer controlID = new StringBuffer();
        String[] fields = s1.toString().split("\\.");
        for (int i = 0; i < fields.length; i++) {
            if (i == 0) {
                controlID.append(fields[i]);
            } else {
                controlID.append(StringUtils.firstCharToUpperCase(fields[i]));
            }
        }
        return controlID.toString();
    }

    public static boolean indexOfList(List list, String value, String attribute) {
        boolean b = false;
        if (list == null) {
            return b;
        }
        try {
            for (Object o : list) {
                String str = Reflections.invokeGetter(o, attribute).toString();
                if (!StringUtils.isEmpty(str) && str.equals(value)) {
                    b = true;
                    break;
                }
            }
        } catch (IllegalArgumentException e) {
            for (Object o : list) {
                if (o.equals(value)) {
                    b = true;
                    break;
                }
            }
        }
        return b;
    }
}
